package router

import (
	"bufio"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"miaoyu/internal/consts"
	modelAdmin "miaoyu/internal/model/admin"
	"miaoyu/internal/service"
	"os"
)

// UrlBuild 路径生成函数
/**

路径 path  规则xx.xx.xxX.do
参数 param
前缀 prefix  xx.xx.xxX
*/

func UrlTranslate(imap *modelAdmin.RouteMap) (string, string, string) {
	var (
		method = "GET"
		urlStr = ""
		prefix = "backend"
		suffix = "do"
		key    = ""
	)
	key = imap.Key
	if imap.Method != "" {
		method = imap.Method
	}
	if imap.Prefix != "" {
		prefix = imap.Prefix
	}
	if imap.Suffix != "" {
		suffix = imap.Suffix
	}

	if imap.NickRoute != "" {
		urlStr = "/" + imap.NickRoute
		pathSlice := gstr.SplitAndTrim(urlStr, "/")
		for index, data := range pathSlice {
			pathSlice[index] = gstr.CaseSnakeFirstUpper(data)
		}
		urlStr = "/" + gstr.Join(pathSlice, "/") + "." + suffix
	} else {
		pathSlice := gstr.SplitAndTrim(prefix+"/"+key, "/")
		for index, data := range pathSlice {
			pathSlice[index] = gstr.CaseSnakeFirstUpper(data)
		}
		urlStr = "/" + gstr.Join(pathSlice, "/") + "." + suffix
	}
	keySlice := gstr.SplitAndTrim(prefix+"/"+key, "/")
	key = gstr.Join(keySlice, "/")
	key = gstr.ToLower(key)
	method = gstr.ToLower(imap.Method)
	//pathSlice := strings.Split(path, "/")
	return key, urlStr, method
}

func MakeRouteMap() []modelAdmin.RouteMap {
	adminList := makeAdminRouteMap()

	for index, val := range adminList {
		if val.Style == "route" {
			key, pattern, method := UrlTranslate(&val)
			val.Pattern = pattern
			val.Method = method
			val.Key = key
			adminList[index] = val
		}
	}
	return adminList
}

func storeRouteMapSimple(imap []modelAdmin.RouteMap) {
	var simpleRouteMap []modelAdmin.RouteMapSimple
	for _, val := range imap {
		if val.Style == "route" {
			simpleRouteMap = append(simpleRouteMap, modelAdmin.RouteMapSimple{
				Key:     val.Key,
				Pattern: val.Pattern,
				Method:  val.Method,
				NoLogin: val.NoLogin,
			})
		}
	}
	consts.RouteMap = append(consts.RouteMap, simpleRouteMap...)
}
func WriteRouteMap(imap []modelAdmin.RouteMap) {
	os.Remove("route.map.txt")
	file, err := os.OpenFile("route.map.txt", os.O_CREATE, 0)

	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	for index, val := range imap {
		if val.Style == "route" {
			_, err = writer.WriteString("路由" + gconv.String(index) + "; desc= " + val.Desc + "\n")
			_, err = writer.WriteString("key= " + val.Key + "\n")
			_, err = writer.WriteString("route= " + val.Pattern + "\n")
			if err != nil {
				fmt.Println(err)
			}
		}
	}
	writer.Flush()
	return
}

func RegisterRoute(maps []modelAdmin.RouteMap, group *ghttp.RouterGroup) {

	for _, val := range maps {
		if val.Style == "middleware" {
			group.Middleware(val.HandlerFunc)
		} else if val.Style == "route" {
			method := val.Method
			switch method {
			case "get":
				group.GET(val.Pattern, val.Handler)
			case "post":
				group.POST(val.Pattern, val.Handler)
			case "all":
				group.ALL(val.Pattern, val.Handler)
			default:
				group.ALL(val.Pattern, val.Handler)
			}
		}
	}
}

func init() {

	s := g.Server()

	s.BindMiddlewareDefault(service.MiddlewareDefaultResponse)

	s.Group("/", func(group *ghttp.RouterGroup) {

		maps := MakeRouteMap()
		storeRouteMapSimple(maps)
		WriteRouteMap(maps)
		RegisterRoute(maps, group)

	})

}
